<script setup>
import { ref } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import requestUtil from "@/utils/request.js";
import Cookies from "js-cookie";
let router = useRouter();
let route = useRoute();
let choseAddressId = ref();
let addressList = ref([]);
let orderNumber = ref();
let list = window.sessionStorage.getItem("list")
  ? ref(JSON.parse(window.sessionStorage.getItem("list")))
  : ref([]);
const getAddressList = async () => {
  let res = await requestUtil.post("/app/address/", {
    userId: Cookies.get("userId")
  });
  addressList.value = res.data.data;
};
getAddressList();
const onAdd = item => {
  router.push({
    path: "/addressadd",
    query: {
      userId: Cookies.get("userId")
    }
  });
};
const onEdit = item => {
  router.push({
    path: "/addresschange",
    query: {
      id: item.id
    }
  });
};
const onClickLeft = () => {
  router.back();
  // history.go(-1);
};
const onClickRight = async () => {
  console.log(choseAddressId.value);
  if (!choseAddressId.value) {
    ElMessage.warning("请选择收货地址");
    return;
  }
  let res = await requestUtil.put("/app/addOrder/", {
    list: list.value,
    addressId: choseAddressId.value,
    totalPrice: window.sessionStorage.getItem("totalPrice")
  });
  if (res.data.code === 200) {
    let orderNumber = res.data.orderNumber;
    console.log(orderNumber);
    ElMessage.success("下单成功");
    router.push({
      path: "/pay",
      query: {
        orderNumber: orderNumber
      }
    });
  }else{
    ElMessage.warning("下单失败");
  }
};
</script>

<template>
  <div class="address">
    <van-nav-bar
      title="我的收获地址"
      left-text="返回"
      right-text="完成"
      left-arrow
      @click-left="onClickLeft"
      @click-right="onClickRight"
    />
    <van-address-list v-model="choseAddressId" :list="addressList" @add="onAdd" @edit="onEdit" />
  </div>
</template>

<style scoped>
</style>